package cn.org.gs.channel;

import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
// SocketChannel主要是用来处理网络I/O的通道
public class SocketChannelDemo {
    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("www.baidu.com", 80));

        // 方式二创建
//        SocketChannel socketChannel1 = SocketChannel.open();
//        socketChannel1.connect(new InetSocketAddress("www.baidu.com", 80));

//        socketChannel.isOpen(); // 测试 SocketChannel 是否为 open 状态
//        socketChannel.isConnected(); //测试 SocketChannel 是否已经被连接
//        socketChannel.isConnectionPending(); //测试 SocketChannel 是否正在进行连接
//        socketChannel.finishConnect(); //校验正在进行套接字连接的 SocketChannel是否已经完成连
        // 设置非阻塞模式
        socketChannel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 设置和获取参数
        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, Boolean.TRUE)
            .setOption(StandardSocketOptions.TCP_NODELAY, Boolean.TRUE);
        System.out.println(socketChannel.getOption(StandardSocketOptions.SO_KEEPALIVE));
        System.out.println(socketChannel.getOption(StandardSocketOptions.SO_RCVBUF));

        socketChannel.read(buffer);
        socketChannel.close();
        System.out.println("read over!");
    }
}
